package com.mdnote.practice.binary_tree;

/**
 * @author Rhythm-2019
 * @date 2020/10/1
 * @description 构造最大二叉树
 */
public class LeetCode654 {

    public TreeNode constructMaximumBinaryTree(int[] nums) {
        if (nums.length == 0) {
            return null;
        }
        return construct(0, nums.length - 1, nums);
    }

    /**
     * 递归构建最大二叉树，确定遍历方式【前序遍历】，当前节点需要完成的任务，想办法构建自己
     */
    private TreeNode construct(int left, int right, int[] nums) {
        // Terminator
        if (left > right) {
            return null;
        }
        // Process
        int max = Integer.MIN_VALUE;
        int maxIndex = 0;
        for (int i = left; i <= right; i++) {
            if (nums[i] > max) {
                max = nums[i];
                maxIndex = i;
            }
        }
        TreeNode treeNode = new TreeNode(max);
        // Drill dwon
        treeNode.left = construct(left, maxIndex - 1, nums);
        treeNode.right = construct(maxIndex + 1, right, nums);
        // Restore current data
        return treeNode;
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }
}
